<template>
  <div class="preview" :key="key">
    <div
      class="preview-item"
      v-for="(item, index) in list"
      :key="item.id + index"
      :style="[
        getComputedStyle(item),
        { transform: `scale(${scaleW}, ${scaleH})` },
      ]"
    >
      <component
        v-if="!item.UPDATE"
        :is="`lcd-sider-${item.key}`"
        :id="item.id"
        :key="`lcd-sider-${item.key}~${item.id}`"
        :prop="useProp(item.id)"
        :global="useGlobal(item.id)"
        @mapChange="handleMapChange"
      ></component>
    </div>
  </div>
</template>

<script>
import view from '@/mixins/viewer'

export default {
  name: 'Preview',
  mixins: [view],
  data() {
    return {
      key: Date.now(),
    }
  },
  mounted() {
    this.init()
    this.transformStyle()
  },

  methods: {
    init() {
      const data = localStorage.getItem('preview')
      if (data && !this.list.length) {
        // 初始化
        this.list = data ? JSON.parse(data) : []
      }
      const graph = localStorage.getItem('graph')
      if (graph) {
        // 初始化
        this.graph = graph ? JSON.parse(graph) : []
      }
      try {
        addEventListener('resize', this.transformStyle)
        addEventListener('storage', this.transformData)
      } catch (error) {
        console.log(error)
      }
    },
    transformStyle() {
      const data = localStorage.getItem('canvasStyle')
      const { clientWidth, clientHeight } = document.documentElement
      if (data) {
        const { width, height } = JSON.parse(data)
        this.scaleW = clientWidth / width
        this.scaleH = clientHeight / height
      }
    },
    transformData(e) {
      if (e.key == 'preview') {
        this.list = e.newValue ? JSON.parse(e.newValue) : []
      }
      if (e.key == 'canvasStyle') {
        this.transformStyle()
      }
    },
    handleMapChange(data) {
      this.list = this.list.map((m) => {
        if (this.graph?.map1.includes(m.key)) {
          return {
            ...m,
            global: [
              {
                key: 'mapLevel',
                value: data.mapLevel,
                isWork: true,
              },
              {
                key: 'mapCode',
                value: data.mapCode,
                isWork: true,
              },
            ],
          }
        } else {
          return m
        }
      })
    },
  },
  beforeDestroy() {
    removeEventListener('resize', this.transformStyle)
    removeEventListener('storage', this.transformData)
  },
}
</script>

<style lang="less" scoped>
.preview {
  position: relative;
  width: 100%;
  height: 100%;
  .preview-item {
    position: absolute;
    overflow: hidden;
    transform-origin: 0 0;
  }
}
</style>
